package com.ycz;

import lombok.SneakyThrows;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.Map;

/**
 * @author ycz
 * @date 2021/6/18
 *
 * 将mapper接口代理类注册到spring中
 */
public class MapperBeanDefinitionRegistry4 implements ImportBeanDefinitionRegistrar, ResourceLoaderAware {

    final String classPathPre = "classpath*:";

    private ResourceLoader resourceLoader;

    @SneakyThrows
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

        Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(MyMapperScan4.class.getName());
        // 获取到扫描包
        String packageName = (String) annotationAttributes.get("value");
        ResourcePatternResolver resolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
        MetadataReaderFactory metaReader = new CachingMetadataReaderFactory(resourceLoader);
        Resource[] resources = resolver.getResources((classPathPre +
                packageName.replace('.', '/') + "/*.class"));

        // 获取到包下所有的类
        for (Resource r : resources) {
            MetadataReader reader = metaReader.getMetadataReader(r);
            // 获取包下所有的类
            System.out.println(reader.getClassMetadata().getClassName());
            BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
            AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
            // 设置beanClass
            beanDefinition.setBeanClass(MapperFactoryBean4.class);
            // 设置注册beanDefinition（MapperFactoryBean）的构造方法
            beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(reader.getClassMetadata().getClassName());
            // 注册 bean
            registry.registerBeanDefinition(reader.getClassMetadata().getClassName(),beanDefinition);
        }
    }


    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }
}
